<!-- src/view/maintenanceRecord.vue -->
<!-- src/view/maintenanceRecord.vue -->
<template>
  <div class="maintenance-record-container">
    <h1>设备维护记录</h1>

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="query" label-width="100px" inline>
        <el-form-item label="设备ID">
          <el-input v-model="query.equipment_id" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="技术员ID">
          <el-input v-model="query.technician_id" placeholder="请输入技术员ID" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchMaintenanceRecords">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增按钮 -->
    <div class="toolbar">
      <el-button type="primary" @click="openAddDialog">新增维护记录</el-button>
    </div>

    <!-- 维护记录表格 -->
    <el-table
        :data="pagedData"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
    >
      <el-table-column prop="id" label="ID" width="80" sortable />
      <el-table-column prop="equipment_id" label="设备ID" width="100" />
      <el-table-column prop="maintenance_date" label="维护日期" width="150" />
      <el-table-column prop="description" label="描述" width="200" />
      <el-table-column prop="cost" label="费用" width="100" />
      <el-table-column prop="technician_id" label="技术员ID" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button
              size="small"
              type="danger"
              @click="confirmDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="tableData.length > 0"
        background
        layout="prev, pager, next, sizes, total"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="tableData.length"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; justify-content: center;"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="editForm.id ? '编辑维护记录' : '新增维护记录'"
        width="500px"
    >
      <el-form
          :model="editForm"
          label-width="100px"
          ref="maintenanceRecordForm"
      >
        <el-form-item
            label="设备ID"
            prop="equipment_id"
            :rules="[{ required: true, message: '请输入设备ID', trigger: 'blur' }]"
        >
          <el-input-number
              v-model="editForm.equipment_id"
              :min="1"
              style="width: 100%"
              :disabled="!!editForm.id"
          />
        </el-form-item>
        <el-form-item
            label="维护日期"
            prop="maintenance_date"
            :rules="[{ required: true, message: '请选择维护日期', trigger: 'change' }]"
        >
          <el-date-picker
              v-model="editForm.maintenance_date"
              type="date"
              placeholder="选择维护日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item
            label="描述"
            prop="description"
            :rules="[{ required: true, message: '请输入描述', trigger: 'blur' }]"
        >
          <el-input
              v-model="editForm.description"
              type="textarea"
              placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item
            label="费用"
            prop="cost"
            :rules="[{ required: true, message: '请输入费用', trigger: 'blur' }]"
        >
          <el-input-number
              v-model="editForm.cost"
              :min="0"
              :precision="2"
              :step="0.01"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item
            label="技术员ID"
            prop="technician_id"
            :rules="[{ required: true, message: '请输入技术员ID', trigger: 'blur' }]"
        >
          <el-input-number
              v-model="editForm.technician_id"
              :min="1"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import maintenanceRecordApi from '../api/maintenanceRecordApi.js';
import equipmentApi from '../api/equipmentApi.js';

// 数据状态
const tableData = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const maintenanceRecordForm = ref(null);

// 分页参数
const page = ref(1);
const pageSize = ref(5);

// 计算分页数据
const pagedData = computed(() => {
  if (!Array.isArray(tableData.value)) {
    return [];
  }
  const start = (page.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 查询条件
const query = reactive({
  equipment_id: '',
  technician_id: ''
});

// 表单数据
const editForm = reactive({
  id: null,
  equipment_id: null,
  maintenance_date: null,
  description: '',
  cost: 0,
  technician_id: null
});

// 加载维护记录列表
const loadMaintenanceRecords = async () => {
  loading.value = true;
  try {
    const res = await maintenanceRecordApi.all();
    // 正确处理响应数据
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : [];
      // 按ID排序
      tableData.value.sort((a, b) => a.id - b.id);
    } else {
      tableData.value = [];
      ElMessage.error(res?.msg || '数据加载失败');
    }
  } catch (err) {
    console.error('加载维护记录列表失败:', err);
    tableData.value = [];
    ElMessage.error('加载维护记录列表失败: ' + (err.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 查询维护记录
const searchMaintenanceRecords = async () => {
  loading.value = true;
  try {
    const res = await maintenanceRecordApi.all(query);
    // 正确处理响应数据
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : [];
      // 按ID排序
      tableData.value.sort((a, b) => a.id - b.id);
    } else {
      tableData.value = [];
      ElMessage.error(res?.msg || '查询失败');
    }
    page.value = 1;
  } catch (err) {
    console.error('查询维护记录失败:', err);
    tableData.value = [];
    ElMessage.error('查询维护记录失败: ' + (err.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 重置查询
const resetSearch = () => {
  query.equipment_id = '';
  query.technician_id = '';
  loadMaintenanceRecords();
};

// 分页事件处理
const handlePageChange = (newPage) => {
  page.value = newPage;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  page.value = 1;
};

// 打开新增对话框
const openAddDialog = () => {
  Object.assign(editForm, {
    id: null,
    equipment_id: null,
    maintenance_date: '',
    description: '',
    cost: 0,
    technician_id: null
  });
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (record) => {
  // 深拷贝记录对象，避免修改原始数据
  const recordCopy = { ...record };
  
  // 确保日期字段格式正确
  if (recordCopy.maintenance_date) {
    // 如果是字符串格式的日期，直接使用
    if (typeof recordCopy.maintenance_date === 'string') {
      // 检查是否是完整日期格式（包含时间），如果是则只取日期部分
      if (recordCopy.maintenance_date.includes('T')) {
        recordCopy.maintenance_date = recordCopy.maintenance_date.split('T')[0];
      } else if (recordCopy.maintenance_date.includes(' ')) {
        recordCopy.maintenance_date = recordCopy.maintenance_date.split(' ')[0];
      }
    } 
    // 如果是Date对象，转换为YYYY-MM-DD格式的字符串
    else if (recordCopy.maintenance_date instanceof Date) {
      const date = recordCopy.maintenance_date;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      recordCopy.maintenance_date = `${year}-${month}-${day}`;
    }
  }
  
  Object.assign(editForm, recordCopy);
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  try {
    // 创建提交数据的副本
    const submitData = { ...editForm };
    
    // 确保日期字段格式正确
    if (submitData.maintenance_date) {
      if (submitData.maintenance_date instanceof Date) {
        const date = submitData.maintenance_date;
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        submitData.maintenance_date = `${year}-${month}-${day}`;
      } else if (typeof submitData.maintenance_date === 'string') {
        // 验证日期格式是否正确
        const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
        if (!dateRegex.test(submitData.maintenance_date)) {
          ElMessage.error('日期格式不正确，请重新选择');
          return;
        }
      }
    }
    
    if (editForm.id) {
      // 编辑
      const res = await maintenanceRecordApi.edit(submitData);
      if (res && res.code === 200) {
        ElMessage.success('更新成功');
        dialogVisible.value = false;
        loadMaintenanceRecords();
      } else {
        ElMessage.error(res?.msg || '更新失败');
      }
    } else {
      // 新增
      if (!submitData.equipment_id || !submitData.maintenance_date || !submitData.description ||
          submitData.cost === null || !submitData.technician_id) {
        ElMessage.warning('请填写完整信息');
        return;
      }

      const res = await maintenanceRecordApi.add(submitData);
      if (res && res.code === 200) {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        loadMaintenanceRecords();
        
        // 更新对应设备的最后维护日期
        try {
          const equipmentRes = await equipmentApi.list();
          if (equipmentRes && equipmentRes.code === 200) {
            const equipmentList = equipmentRes.data;
            const targetEquipment = equipmentList.find(e => e.id === submitData.equipment_id);
            if (targetEquipment) {
              const updatedEquipment = { ...targetEquipment };
              updatedEquipment.last_maintenance = submitData.maintenance_date;
              await equipmentApi.edit(updatedEquipment);
            }
          }
        } catch (equipmentError) {
          console.error('更新设备最后维护日期失败:', equipmentError);
        }
      } else {
        ElMessage.error(res?.msg || '新增失败');
      }
    }
  } catch (err) {
    console.error('操作失败:', err);
    ElMessage.error('操作失败: ' + (err.message || '请检查网络连接'));
  }
};

// 删除维护记录
const confirmDelete = async (id) => {
  ElMessageBox.confirm(
      '确定要删除该维护记录吗？此操作不可恢复。',
      '删除确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(async () => {
    try {
      const res = await maintenanceRecordApi.del(id);
      if (res && res.code === 200) {
        ElMessage.success('删除成功');
        loadMaintenanceRecords();
      } else {
        ElMessage.error(res?.msg || '删除失败');
      }
    } catch (err) {
      console.error('删除失败:', err);
      ElMessage.error('删除失败: ' + (err.message || '请检查网络连接'));
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 初始化加载数据
onMounted(() => {
  loadMaintenanceRecords();
});
</script>

<style scoped>
.maintenance-record-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
  text-align: right;
}
</style>
